var webwx = require('./webwx');

var synccheck = webwx.synccheck;
var webwxsync = webwx.webwxsync;
// 黑名单
const BLACK_LIST = 'specialUser';

/**
 * 消息处理
 * @param filters 过滤
 * @param transducers 并行处理
 * @returns {function(*, *=)}
 */
function handleMsg(filters, transducers) {
    return (addMsgList, wxSession) => {
        var replys = addMsgList
            .filter(o => o.ToUserName == wxSession.username)
            .filter(o => (BLACK_LIST.indexOf(o.FromUserName) < 0));  // 不是特殊用户

        // 自定义过滤器
        filters.forEach(f => {
            replys = replys.filter(f(wxSession));
        });

        transducers.push(wxSession => o => Promise.resolve(o));

        transducers.forEach(f => {
            replys = replys.map(f(wxSession));
        });

        replys.map(r => r.then(o => console.log('执行一次对话')).catch(console.error));
    }
}

/**
 * 不断循环获取
 * @param filters
 * @param transducers
 * @returns {function(*=)}
 */
function robot(filters, transducers) {
    return (wxSession) => {
        synccheck(wxSession)
            .then(webwxsync(handleMsg(filters, transducers)))
            .then(robot(filters, transducers))
            .catch(console.error);
    }
}

exports.robot = robot;